package com.leyou.statis.service.impl;

import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.IdWorker;
import com.leyou.item.inter.api.ICategoryService;
import com.leyou.item.inter.api.IGoodsService;
import com.leyou.item.inter.pojo.Category;
import com.leyou.item.inter.pojo.Sku;
import com.leyou.item.inter.pojo.Spu;
import com.leyou.order.inter.api.IOrderService;
import com.leyou.order.inter.pojo.OrderDetail;
import com.leyou.statis.config.IdWorkerProperties;
import com.leyou.statis.dto.PolymerDTO;
import com.leyou.statis.dto.StatisVO;
import com.leyou.statis.mapper.StatisMapper;
import com.leyou.statis.pojo.Statis;
import com.leyou.statis.service.StatisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author zqq
 * @ClassName StatisServiceImpl
 * @Description
 * @date 2020/4/6-17:39
 */
@Slf4j
@Service
public class StatisServiceImpl implements StatisService {

    @Autowired
    private StatisMapper statisMapper;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private IdWorkerProperties idWorkerProperties;

    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private ICategoryService iCategoryService;

    @Override
    public Result<List<StatisVO>> queryStatisByDto(PolymerDTO dto) {
        if(dto.getType() == 1){
            List<Statis> statisList = null;
            try {
                statisList = this.statisMapper.selectStatisBySpu(dto.getCurYear(), dto.getCurMonth(), dto.getTotal());
            } catch (Exception e) {
                log.error("sql异常", e);
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }
            if(statisList.size() > 0){
                List<StatisVO> result = new ArrayList<>();
                StatisVO vo = null;
                for (Statis statis : statisList) {
                    vo = new StatisVO();
                    vo.setNum(statis.getNum());
                    vo.setTotalPrice(statis.getTotalPrice());
                    vo.setSpuName(statis.getSpuName());
                    result.add(vo);
                }
                return Result.newSuccess(result);
            }
        }else if(dto.getType() == 2){
            List<Statis> statisList = null;
            try {
                statisList = this.statisMapper.selectStatisByCategory(dto.getCurYear(), dto.getCurMonth(), dto.getTotal());
            } catch (Exception e) {
                log.error("sql异常", e);
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }
            if(statisList.size() > 0){
                List<StatisVO> result = new ArrayList<>();
                StatisVO vo = null;
                for (Statis statis : statisList) {
                    vo = new StatisVO();
                    vo.setNum(statis.getNum());
                    vo.setTotalPrice(statis.getTotalPrice());
                    vo.setCategoryName(statis.getCategoryName());
                    result.add(vo);
                }
                return Result.newSuccess(result);
            }
        }
        return Result.newSuccess();
    }

    @Override
    public Result<List<StatisVO>> queryStatisByQuarter(String year) {
        List<Statis> statisList = null;
        try {
            statisList = this.statisMapper.selectStatisByQuarter(year);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        List<StatisVO> result = new ArrayList<>();
        StatisVO vo = null;
        if(statisList.size() >0 && statisList.size() <4){
            for(int i=0;i<4;i++){
                vo = new StatisVO();
                for (Statis statis : statisList) {
                    if(statis.getQuarter() == (i+1)){
                        vo.setNum(statis.getNum());
                        vo.setTotalPrice(statis.getTotalPrice());
                        vo.setQuarter(i+1);
                        continue;
                    }
                }
                if(vo.getQuarter() == null){
                    vo.setQuarter(i+1);
                    vo.setNum(0);
                    vo.setTotalPrice(0L);
                }
                result.add(vo);
            }
        }else if(statisList.size() == 4){
            for (Statis statis : statisList) {
                vo = new StatisVO();
                vo.setNum(statis.getNum());
                vo.setTotalPrice(statis.getTotalPrice());
                vo.setQuarter(statis.getQuarter());
                result.add(vo);
            }
        }
        if(result.size() == 0)
            return Result.newSuccess();
        return Result.newSuccess(result);
    }

    @Override
    public Result<List<StatisVO>> queryStatisByMonth(String year) {
        List<Statis> statisList = null;
        try {
            statisList = this.statisMapper.selectStatisByMonth(year);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        if(statisList.size() > 0){
            List<StatisVO> result = this.setStatisData(statisList);
            return Result.newSuccess(result);
        }else{
            return Result.newSuccess();
        }
    }

    @Override
    public Result<Map<Integer, List<StatisVO>>> queryStatisByYears() {
        Integer[] yearArr = {2018,2019,2020};
        String years = StringUtils.join(yearArr, ",");
        List<Statis> statisList = null;
        try {
            statisList = this.statisMapper.selectStatisByYears(years);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        List<Statis> oneList = new ArrayList<>();
        List<Statis> twoList = new ArrayList<>();
        List<Statis> threeList = new ArrayList<>();
        if(statisList.size() > 0){
            for (Statis statis : statisList) {
                if(statis.getYear().equals(yearArr[0])){
                    oneList.add(statis);
                }else if(statis.getYear().equals(yearArr[1])){
                    twoList.add(statis);
                }else if(statis.getYear().equals(yearArr[2])){
                    threeList.add(statis);
                }
            }
            Map<Integer, List<StatisVO>> map = new HashMap<>();
            if(oneList.size() > 0){
                List<StatisVO> result = this.setStatisData(oneList);
                map.put(yearArr[0],result);
            }
            if(twoList.size() > 0){
                List<StatisVO> result = this.setStatisData(twoList);
                map.put(yearArr[1],result);
            }
            if(threeList.size() > 0){
                List<StatisVO> result = this.setStatisData(threeList);
                map.put(yearArr[2],result);
            }
            return Result.newSuccess(map);
        }else{
            return Result.newSuccess();
        }
    }

    public List<StatisVO> setStatisData(List<Statis> statisList){
        List<StatisVO> result = new ArrayList<>();
        StatisVO vo = null;
        if(statisList.size() >0 && statisList.size() <12){
            for(int i=0;i<12;i++){
                vo = new StatisVO();
                for (Statis statis : statisList) {
                    if(statis.getMonth() == (i+1)){
                        vo.setNum(statis.getNum());
                        vo.setTotalPrice(statis.getTotalPrice());
                        vo.setMonth(i+1);
                    }
                }
                if(vo.getMonth() == null){
                    vo.setNum(0);
                    vo.setTotalPrice(0L);
                    vo.setMonth(i+1);
                }

                result.add(vo);
            }
        }else if(statisList.size() == 12){
            for (Statis statis : statisList) {
                vo = new StatisVO();
                vo.setNum(statis.getNum());
                vo.setTotalPrice(statis.getTotalPrice());
                vo.setMonth(statis.getMonth());
                result.add(vo);
            }
        }
        return result;
    }

    @Override
    public void addStatis(Long id) {
        Result<List<OrderDetail>> listResult = null;
        try {
            listResult = iOrderService.queryOrderDetail(id);
        } catch (Exception e) {
            log.error(e.getMessage());
            return;
        }
        List<OrderDetail> detailList = listResult.getData();
        if(detailList.size() == 0)
            return;
        IdWorker idWorker = new IdWorker(idWorkerProperties.getWorkerId(),idWorkerProperties.getDatacenterId());
        detailList.forEach(detail ->{
            Result<Sku> skuResult = iGoodsService.querySkuById(detail.getSkuId());
            if(!skuResult.success() || skuResult.getData() == null)
                return;
            List<Statis> statisList = statisMapper.selectStatisByDate(skuResult.getData().getSpuId(),new Date());
            if(statisList.size() > 0){
                Statis statis = new Statis();
                statis.setId(statisList.get(0).getId());
                statis.setNum(statisList.get(0).getNum()+detail.getNum());
                statis.setTotalPrice(statisList.get(0).getTotalPrice()+detail.getNum()*detail.getPrice());
                this.statisMapper.updateByPrimaryKeySelective(statis);
            }else{
                Result<Spu> spuResult = iGoodsService.querySpuById(skuResult.getData().getSpuId());
                if(!spuResult.success() || spuResult.getData() == null)
                    return;
                Result<Category> categoryResult = iCategoryService.queryCategoryById(spuResult.getData().getCid3());
                if(!categoryResult.success() || categoryResult.getData() == null)
                    return;
                Statis statis = new Statis();
                statis.setId(idWorker.nextId());
                statis.setSpuId(spuResult.getData().getId());
                statis.setSpuName(spuResult.getData().getTitle());
                statis.setCId(spuResult.getData().getCid3());
                statis.setCategoryName(categoryResult.getData().getName());
                statis.setCreateDate(new Date());
                statis.setNum(detail.getNum());
                statis.setTotalPrice(detail.getPrice()*detail.getNum());
                this.statisMapper.insertSelective(statis);
            }
        });
    }
}
